<?php

declare(strict_types=1);

namespace Modules\Notice\Models;

use Catch\Base\CatchModel as Model;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

/**
 * 查询IP信息
 */
class IpGeo extends Model
{

    protected static Logger $logger;

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        self::$logger = new Logger('ip');
        $log_path = storage_path('logs/ip.log');
        self::$logger->pushHandler(new RotatingFileHandler($log_path, 30));
    }

    /**
     * 查询IP的省市区
     * @param $phone
     * @param $code
     */
    public static function geo($ip)
    {
        if (!defined('CURL_SSLVERSION_TLSv1_2')) {
            define('CURL_SSLVERSION_TLSv1_2', 6);
        }
        $province = '未知';
        $city = '未知';
        $area = '未知';
        $ipInfo = Http::post('https://api.ipplus360.com/ip/geo/v1/city?key=' . getenv('IP_KEY') . '&ip=' . $ip . '&coordsys=WGS84');
        $ipInfo = $ipInfo->json();
        self::$logger->info('ipplus360 info:', $ipInfo);
        if (!empty($ipInfo['code']) && ($ipInfo['code'] == 'Success') && !empty($ipInfo['data'])) {
            $province = $ipInfo['data']['prov'] ?? '未知';
            $city = $ipInfo['data']['city'] ?? '未知';
            $area = $ipInfo['data']['district'] ?? '未知';
        }
        return $ipInfo['data'];
        return [
            'province' => $province,
            'city' => $city,
            'area' => $area,
        ];
    }
}
